<template>
  <div>
    <div slot="header" class="clearfix">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        <el-breadcrumb-item>修改信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-divider content-position="center">修改个人信息</el-divider>
    <el-row :gutter="20">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-col :span="24">
          <!-- 用户头像 -->
          <el-form-item label="用户头像">
            <!-- 头衔缩略图 -->
            <pan-thumb :image="image" />
            <!-- 文件上传按钮 -->
            <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像</el-button>

            <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
            @crop-upload-success：上传成功后的回调-->
            <image-cropper
              v-show="imagecropperShow"
              :width="300"
              :height="300"
              :key="imagecropperKey"
              :url="'/uploadImgFile/userAvatar/'"
              :params="user"
              field="file"
              @close="closeImage"
              @crop-upload-success="cropSuccess"
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="formData.nickname"
              placeholder="请输入昵称"
              clearable
              :style="{width: '100%'}"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="电话号码" prop="phoneNumber">
            <el-input
              v-model="formData.phoneNumber"
              placeholder="请输入您的电话号码"
              clearable
              :style="{width: '100%'}"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="生日" prop="birth">
            <el-date-picker
              v-model="formData.birth"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{width: '100%'}"
              placeholder="请输入您的生日"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import PanThumb from "@/components/avatar-upload/PanThumb";
import ImageCropper from "@/components/avatar-upload/ImageCropper";
import { deleteImgFile } from "@/api/oss";
import { modifiedUserInfo } from "@/api/user";

export default {
  components: {
    PanThumb,
    ImageCropper
  },
  data() {
    return {
      user: {
        id: "",
        type: "",
        avatar: ""
      },
      formData: {
        username: undefined,
        nickname: undefined,
        phoneNumber: undefined,
        birth: "2000-01-01"
      },
      rules: {
        nickname: [
          {
            required: true,
            message: "请输入昵称",
            trigger: "blur"
          }
        ],
        phoneNumber: [
          {
            required: true,
            message: "请输入您的电话号码",
            trigger: "blur"
          }
        ],
        birth: [
          {
            required: true,
            message: "请输入您的生日",
            trigger: "change"
          }
        ]
      },
      avatarAction: "https://jsonplaceholder.typicode.com/posts/",
      avatarfileList: [],
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      image: this.$store.state.user.avatar
    };
  },
  computed: {},
  created() {
    this.user = JSON.parse(this.$route.query.user);
  },
  watch: {},
  mounted() {},
  methods: {
    submitForm() {
      this.$refs["elForm"].validate(valid => {
        if (!valid) return;
        // TODO 提交表单
      });
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
    },
    // 上传之前，检测文件大小
    avatarBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      return isRightSize;
    },
    // 上传成功后的回调函数
    cropSuccess(data) {
      // 使用该属性保存上传之前的头像
      var oldImg = this.image;
      this.imagecropperShow = false;
      this.user.avatar = this.image = data.data.url;
      this.update();
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
      // 删除旧图片
      this.deleteAvatar(oldImg);
      this.$store.state.user.avatar = this.image;
      console.log(this.$store);
    },
    // 删除图片
    async deleteAvatar(oldImg) {
      const { data } = await deleteImgFile(oldImg);
    },
    // 更新用户信息
    async update() {
      const { data } = await modifiedUserInfo(
        this.user.type,
        this.user.id,
        this.user.avatar
      );
    },
    // 关闭上传组件
    closeImage() {
      this.imagecropperShow = false;
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
    }
  }
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
